package com.jfinalplus.plugin.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.util.Assert;

import com.jfinal.kit.PathKit;
import com.jfinal.plugin.IPlugin;

/**
 * SpringPlugin.
 */
public class SpringPlugin implements IPlugin {

	private static boolean isStarted = false;
	private String[] configurations;
	private ApplicationContext ctx;
	
	public SpringPlugin() {}

	public SpringPlugin(ApplicationContext ctx) {
		this.setApplicationContext(ctx);
	}
	
	public SpringPlugin(String... configurations) {
		this.configurations = configurations;
	}

	public void setApplicationContext(ApplicationContext ctx) {
		Assert.notNull(ctx, "ApplicationContext can not be null.");
		this.ctx = ctx;
	}
	
	public ApplicationContext getApplicationContext() {
		return this.ctx ;
	}

	public boolean start() {
		if (isStarted) {
			return true;
		}else if (!isStarted && configurations != null){
			ctx = new FileSystemXmlApplicationContext(configurations);
		}else {
			ctx = new FileSystemXmlApplicationContext(PathKit.getWebRootPath() + "/WEB-INF/applicationContext.xml");
		}
		Assert.notNull(ctx, "ApplicationContext can not be null.");
		IocKit.init(ctx);
		return isStarted = true;
	}

	public boolean stop() {
		ctx = null;
		isStarted = false;
		return true;
	}
}
